﻿using Microsoft.AspNetCore.Identity;

namespace Admin.NET.Core.Service;
/// <summary>
/// 账号绑定服务
/// </summary>
[ApiDescriptionSettings(Order = 100)]
public class UserBindService : IDynamicApiController, ITransient
{
    private readonly UserManager _userManager;
    private readonly SqlSugarRepository<UserBind> _rep;
    private readonly SqlSugarRepository<SysUser> _sysUserRep;
    private readonly SysAuthService _sysAuthServiceRep;
    
    public UserBindService(SqlSugarRepository<UserBind> rep, SysAuthService sysAuthServiceRep,SqlSugarRepository<SysUser> sysUserRep,UserManager userManager)
    {
        _rep = rep;
        _sysAuthServiceRep = sysAuthServiceRep;
        _sysUserRep = sysUserRep;
        _userManager = userManager;
    }

    /// <summary>
    /// 分页查询账号绑定
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    public async Task<SqlSugarPagedList<UserBindOutput>> Page(UserBindInput input)
    {
        var query = _rep.AsQueryable()
            //.Where(u => u.DingUserId == input.DingUserId.Trim())
            .WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), u =>
                u.DingUserId.Contains(input.SearchKey.Trim())
            )
            .Where( u => u.DingUserId.Contains(input.DingUserId ?? "none") || u.UserId == _userManager.UserId)
            //.WhereIF(input.UserId>0, u => u.UserId == input.UserId)
            //处理外键和TreeSelector相关字段的连接
            .LeftJoin<SysUser>((u, userid) => u.UserId == userid.Id )
            .OrderBy(u => u.CreateTime)
            .Select((u, userid) => new UserBindOutput
            {
                Id = u.Id,
                DingUserId = u.DingUserId,
                UserId = u.UserId, 
                UserIdAccount = userid.Account,
                CreateUserName = u.CreateUserName,
                UpdateUserName = u.UpdateUserName,
            });
        return await query.ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 分页查询账号绑定
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [AllowAnonymous]
    [ApiDescriptionSettings(Name = "DingPage")]
    public async Task<SqlSugarPagedList<UserBindOutput>> DingPage(UserBindInput input)
    {
        var query = _rep.AsQueryable()
            .Where(u => u.DingUserId == input.DingUserId.Trim())
            .WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), u =>
                u.DingUserId.Contains(input.SearchKey.Trim())
            )
            //.WhereIF(!string.IsNullOrWhiteSpace(input.DingUserId), u => u.DingUserId.Contains(input.DingUserId.Trim()))
            //.WhereIF(input.UserId > 0, u => u.UserId == input.UserId)
            //处理外键和TreeSelector相关字段的连接
            .LeftJoin<SysUser>((u, userid) => u.UserId == userid.Id)
            .OrderBy(u => u.CreateTime)
            .Select((u, userid) => new UserBindOutput
            {
                Id = u.Id,
                DingUserId = u.DingUserId,
                UserId = u.UserId,
                UserIdAccount = userid.Account,
                CreateUserName = u.CreateUserName,
                UpdateUserName = u.UpdateUserName,
            });
        return await query.ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加账号绑定
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    public async Task<long> Add(AddUserBindInput input)
    {
        var entity = input.Adapt<UserBind>();
        await _rep.InsertAsync(entity);
        return entity.Id;
    }

    /// <summary>
    /// 删除账号绑定
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    public async Task Delete(DeleteUserBindInput input)
    {
        var entity = await _rep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        //await _rep.FakeDeleteAsync(entity);   //假删除
        await _rep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 更新账号绑定
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    public async Task Update(UpdateUserBindInput input)
    {
        var entity = input.Adapt<UserBind>();
        await _rep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 获取账号绑定
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    public async Task<UserBind> Detail([FromQuery] QueryByIdUserBindInput input)
    {
        return await _rep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 获取账号绑定列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    public async Task<List<UserBindOutput>> List([FromQuery] UserBindInput input)
    {
        return await _rep.AsQueryable().Select<UserBindOutput>().ToListAsync();
    }

    /// <summary>
    /// 获取用户表UserId列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [AllowAnonymous]
    [ApiDescriptionSettings(Name = "SysUserUserIdDropdown"), HttpGet]
    public async Task<dynamic> SysUserUserIdDropdown()
    {
        return await _rep.Context.Queryable<SysUser>()
                .Select(u => new
                {
                    Label = u.Account,
                    Value = u.Id
                }
                ).ToListAsync();
    }

    /// <summary>
    /// 手机号登录
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [AllowAnonymous]
    [DisplayName("钉钉登录")]
    public async Task<LoginOutput> LoginDingDing([Required] LoginDingDingInput input)
    {
        var userBind = await _rep.GetByIdAsync(input.Id);
        if(userBind != null)
        {
            var user = await _sysUserRep.AsQueryable().Includes(t => t.SysOrg).Filter(null, true).FirstAsync(u => u.Id == userBind.UserId);
            _ = user ?? throw Oops.Oh(ErrorCodeEnum.D0009);
            return await _sysAuthServiceRep.CreateToken(user);
        }
        return null;
    }


}

